<script setup>
import { ref, watch, computed } from "vue";
import "@material/web/list/list-item.js";
import "@material/web/switch/switch.js";
import "@material/web/ripple/ripple.js";
import "@material/web/textfield/outlined-text-field.js";
import MaterialDialog from "@/components/MaterialDialog.vue";

const model = defineModel();

const props = defineProps(["type", "placeholder", "disabled"]);

const open = ref(false);
const formValue = ref(model.value);
const disabled = computed(() => props.disabled !== undefined && props.disabled !== false);

watch(() => open.value, newValue => {
  if (newValue) {
    formValue.value = model.value;
  }
});

const inputDialog = ref(null);

function submit() {
  open.value = false;
  model.value = formValue.value;
}
</script>

<template>
  <MaterialDialog ref="inputDialog" :open="open" @close="open = false">
    <template #headline>
      <slot name="headline"></slot>
    </template>

    <template #content>
      <form id="input-form" ref="inputForm" @submit.prevent="submit">
        <md-outlined-text-field :type="props.type" v-model="formValue"
          @keypress.enter.prevent="() => { $refs.inputForm.requestSubmit() }">
        </md-outlined-text-field>
      </form>
    </template>

    <template #actions>
      <md-text-button @click="open = false">取消</md-text-button>
      <md-text-button form="input-form" type="submit">确定</md-text-button>
    </template>
  </MaterialDialog>

  <md-list-item type="button" @click="disabled || (open = true)" :disabled="disabled">
    <div slot="headline" role="presentation">
      <slot name="headline"></slot>
    </div>
    <div slot="supporting-text" role="presentation">
      {{ model || props.placeholder }}
    </div>
  </md-list-item>
</template>

<style scoped>
.input-list-item {
  user-select: none;
  position: relative;
}
</style>